package com.ljkj.cordial.chat.fragment;


import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.activity.GroupChatActivity;
import com.ljkj.cordial.chat.activity.SearchFriendActivity;
import com.ljkj.cordial.chat.adapter.NavRecycleGroupAdapter;
import com.ljkj.cordial.chat.base.BaseFragment;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.GroupSimpleBean;
import com.ljkj.cordial.chat.dao.notify.GroupMemberTable;
import com.ljkj.cordial.chat.dao.notify.GroupTable;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.nic.view.widget.ContainsEmojiEditText;
import com.nic.view.widget.FullyLinearLayoutManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class NavGroupFragment extends BaseFragment implements NavRecycleGroupAdapter.OnGroupItemClickListener {

    Unbinder unbinder;

    @BindView(R.id.rel_empty)
    ImageView relEmpty;
    //    @BindView(R.id.lv_create_group)
//    ListViewForScrollView lvCreateGroup;
//    @BindView(R.id.lv_join_group)
//    ListViewForScrollView lvJoinGroup;
//    @BindView(R.id.sv_content)
//    MyScrollview svContent;
    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.et_input)
    ContainsEmojiEditText etInput;
    //    @BindView(R.id.tv_create_group)
//    TextView tvCreateGroup;
//    @BindView(R.id.tv_join_group)
//    TextView tvJoinGroup;
    @BindView(R.id.ll_add_group)
    LinearLayout llAddGroup;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    //    private NavGroupAdapter createGroupAdapter;
//    private NavGroupAdapter joinGroupAdapter;
    private NavRecycleGroupAdapter groupAdapter;
    private FullyLinearLayoutManager layoutManager;
    private int selectedPosition;
    private boolean isInit;

    public NavGroupFragment() {
        // Required empty public constructor
    }


    @Override
    public int getContentLayoutId() {
        return R.layout.fragment_nav_group;
    }

    @Override
    public void initView(View rootView) {
        unbinder = ButterKnife.bind(this, rootView);
//        createGroupAdapter = new NavGroupAdapter();
//        lvCreateGroup.setAdapter(createGroupAdapter);
//        initJoinAdapter();
//        lvJoinGroup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                selectedPosition = position;
//                GroupSimpleBean cItem = (GroupSimpleBean) parent.getItemAtPosition(position);
//                GroupChatActivity.jumpTo(activity, Canstants.GROUP_CHAT, cItem.getGroupName(), cItem.getGroupId(), cItem.getGroupType());
//            }
//        });
//        lvCreateGroup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                GroupSimpleBean cItem = (GroupSimpleBean) parent.getItemAtPosition(position);
//                GroupChatActivity.jumpTo(activity, Canstants.GROUP_CHAT, cItem.getGroupName(), cItem.getGroupId(), cItem.getGroupType());
//            }
//        });
//        createGroupAdapter.registerDataSetObserver(dataSetObserver);
//        createGroupAdapter.clear();
        llAddGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchFriendActivity.jumpTo(activity, Canstants.SEARCH_TYPE_GROUP);
            }
        });
        groupAdapter = new NavRecycleGroupAdapter();
        groupAdapter.setOnGroupItemClickListener(this);
        layoutManager = new FullyLinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(groupAdapter);
    }

//    private void initJoinAdapter() {
//        joinGroupAdapter = new NavGroupAdapter();
//        lvJoinGroup.setAdapter(joinGroupAdapter);
//        joinGroupAdapter.registerDataSetObserver(dataSetObserver);
//    }

    @Override
    public void onResume() {
        super.onResume();
        queryOfflineData();
    }

//    DataSetObserver dataSetObserver = new DataSetObserver() {
//        @Override
//        public void onChanged() {
//            super.onChanged();
//            if (createGroupAdapter.getCount() == 0 && joinGroupAdapter.getCount() == 0) {
//                if (svContent.getVisibility() == View.VISIBLE) {
//                    svContent.setVisibility(View.GONE);
//                }
//                if (relEmpty.getVisibility() == View.GONE) {
//                    relEmpty.setVisibility(View.VISIBLE);
//                }
//            } else {
//                if (svContent.getVisibility() == View.GONE) {
//                    svContent.setVisibility(View.VISIBLE);
//                }
//                if (relEmpty.getVisibility() == View.VISIBLE) {
//                    relEmpty.setVisibility(View.GONE);
//                }
//
//            }
//        }

//    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
//        createGroupAdapter.unregisterDataSetObserver(dataSetObserver);
//        joinGroupAdapter.unregisterDataSetObserver(dataSetObserver);
    }

    //    /**
//     * 我创建的群
//     *
//     * @param list
//     */
//    public void refreshCreateGroup(List<GroupSimpleBean> list) {
//        if (list == null || list.isEmpty()) {
//            tvCreateGroup.setVisibility(View.GONE);
//            createGroupAdapter.clear();
//            return;
//        }
//        tvCreateGroup.setVisibility(View.VISIBLE);
//        createGroupAdapter.setList(list);
//    }
//
//    /**
//     * 我加入的群
//     *
//     * @param list
//     */
//    public void refreshApplyedGroup(List<GroupSimpleBean> list) {
//        if (list == null || list.isEmpty()) {
//            tvJoinGroup.setVisibility(View.GONE);
//            joinGroupAdapter.clear();
//            return;
//        }
//        tvJoinGroup.setVisibility(View.VISIBLE);
//        joinGroupAdapter.setList(list);
//
//        selection(selectedPosition);
//    }
    public void setGroupData(List<GroupSimpleBean> clist, List<GroupSimpleBean> jList) {
        if ((clist == null || clist.isEmpty()) && (jList == null || jList.isEmpty())) {
            relEmpty.setVisibility(View.VISIBLE);
            return;
        }
        relEmpty.setVisibility(View.GONE);
        GroupSimpleBean cTitle = new GroupSimpleBean();
        cTitle.setTitle("我创建的群聊");
        clist.add(0, cTitle);
        GroupSimpleBean jTitle = new GroupSimpleBean();
        jTitle.setTitle("我参与的群聊");
        jList.add(0, jTitle);
        clist.addAll(jList);
        groupAdapter.setList(clist);
//        selection(selectedPosition);
    }

    @OnClick(R.id.iv_search)
    public void onViewClicked() {
        if (TextUtils.isEmpty(etInput.getText())) {
            return;
        }
        search(etInput.getText().toString());
    }

    public void queryOfflineData() {
        search(null);
    }

    private void search(String search) {
//        Map<String, String> avatars = new HashMap<>();

        ObserverThread.create().onNextThread1(new ObserverThread.OnMulActionListener() {
            @Override
            public void onAction(Object... obj) {
                if (obj == null) {
//                    refreshCreateGroup(null);
//                    refreshApplyedGroup(null);
                    relEmpty.setVisibility(View.VISIBLE);
                    return;
                }
                relEmpty.setVisibility(View.GONE);
                List<GroupSimpleBean> createGroupList = (List<GroupSimpleBean>) obj[0];
                List<GroupSimpleBean> joinGroupList = (List<GroupSimpleBean>) obj[1];
                GroupSimpleBean cTitle = new GroupSimpleBean();
                cTitle.setTitle("我创建的群聊");
                createGroupList.add(0, cTitle);
                GroupSimpleBean jTitle = new GroupSimpleBean();
                jTitle.setTitle("我参与的群聊");
                joinGroupList.add(0, jTitle);
                createGroupList.addAll(joinGroupList);
                groupAdapter.setList(createGroupList);
//                refreshCreateGroup(createGroupList);
//                refreshApplyedGroup(joinGroupList);
//                if (avatars.isEmpty()) {
//                    refreshCreateGroup(createGroupList);
//                    refreshApplyedGroup(joinGroupList);
//                    return;
//                }
//                NetProgressBarDialog progressBarDialog = new NetProgressBarDialog(activity);
//                progressBarDialog.setDes("初始化中...");
//                progressBarDialog.show();
//                AtomicInteger atomicInteger = new AtomicInteger();
//                for (Map.Entry<String, String> entity : avatars.entrySet()) {
//                    AlbumManageUtil.getInstance().downLoadFileFriendAvatar(entity.getKey(), entity.getValue(), new AlbumManageUtil.OnFileResponse() {
//                        @Override
//                        public void onResult(String url, String fileId) {
//                            atomicInteger.getAndIncrement();
//                            if (atomicInteger.intValue() == avatars.size()) {
//                                progressBarDialog.dismiss();
//                                refreshCreateGroup(createGroupList);
//                                refreshApplyedGroup(joinGroupList);
//                            }
//                        }
//                    });
//                }


            }

            @Override
            public Object[] onThreadAction() {
                List<GroupTable> list = TextUtils.isEmpty(search) ? GroupTable.query() : GroupTable.query(search);
                if (list == null || list.isEmpty()) {
                    return null;
                }
                List<GroupSimpleBean> createGroupList = new ArrayList<>();
                List<GroupSimpleBean> joinGroupList = new ArrayList<>();

                for (GroupTable groupTable : list) {
                    GroupSimpleBean g = new GroupSimpleBean();
                    g.setGroupId(groupTable.getGroupId());
                    g.setGroupName(groupTable.getGroupName());
                    g.setGroupType(groupTable.getGroupType());
                    g.setMemberCount(groupTable.getMemberCount());

                    if (!TextUtils.isEmpty(groupTable.getGroupAvatar())) {
                        g.setMemberUserIds(groupTable.getGroupId());
                        g.setMemberAvatarUrls(groupTable.getGroupAvatar());
                    } else {
                        String[] v = GroupMemberTable.getAvatarEntityLoc(groupTable.getGroupId());
                        if (v != null) {
                            g.setMemberUserIds(v[0]);
                            g.setMemberAvatarUrls(v[1]);
                            g.setMemberAvatarPaths(v[2]);
                        }
                    }
//                    if (!TextUtils.isEmpty(g.getMemberAvatarUrls()) || !TextUtils.isEmpty(g.getMemberUserIds())) {
//                        String[] us = g.getMemberAvatarUrls().split(",");
//                        String[] ids = g.getMemberUserIds().split(",");
//                        if (us.length == ids.length) {
//                            for (int i = 0; i < us.length; i++) {
//                                if (!TextUtils.isEmpty(us[i]) && !TextUtils.isEmpty(ids[i])) {
//                                    avatars.put(us[i], ids[i]);
//                                }
//                            }
//                        }
//                    }

                    if (ChatApp.getInstance().getUserId().equals(groupTable.getGroupOwnerId())) {
                        g.setGroupCreateType(GroupSimpleBean.GREATE);
                        createGroupList.add(g);
                    } else {
                        g.setGroupCreateType(GroupSimpleBean.APPLYED);
                        joinGroupList.add(g);
                    }
                }
                return new Object[]{createGroupList, joinGroupList};
            }
        });
    }

    public void selection(int position) {
        recyclerView.scrollToPosition(position);
//        lvJoinGroup.post(new Runnable() {
//            @Override
//            public void run() {
//                lvJoinGroup.smoothScrollToPosition(position);
//            }
//        });
    }


    @Override
    public void onGroupItem(View view, GroupSimpleBean item, int position) {
        selectedPosition = position;
        GroupChatActivity.jumpTo(activity, Canstants.GROUP_CHAT, item.getGroupName(), item.getGroupId(), item.getGroupType());
    }
}
